/**
* edit by wkzq
* date : 2016/7/5
**/

//user name : save in cookie
var uname;
var websocket;
var myImage = new Image(100, 200);
function connectWS() {
	var  wsServer = 'ws://'+window.location.host+'/chat'; 
	websocket = new WebSocket(wsServer); 
	console.log('If you find bugs Please contact @wkzq')
	websocket.onopen = function (evt) { onOpen(evt) }; 
	websocket.onclose = function (evt) { onClose(evt) }; 
	websocket.onmessage = function (evt) { onMessage(evt) }; 
	websocket.onerror = function (evt) { onError(evt) }; 
}

function onOpen(evt) { 
	$('#buttom').before('<h3>Connect success</h3>');
} 
function onClose(evt) { 
	$('#buttom').before('<h3>Disconnected</h3>');
} 
function onMessage(evt) { 
	$('#buttom').before('<p>'+evt.data+'</p>');
} 
function onError(evt) { 
	console.log('Error occured: ' + evt.data); 
}

$('#input-send-btn').on('click',function(){
	var msg = $('#input-text').val();
	$('#buttom').before('<h4 class="me">me&nbsp;&nbsp;:&nbsp;&nbsp;  '+msg+'</h4>');
	websocket.send(uname+'  :  '+msg);
});


function setCookie(cname,cvalue,exdays)
{
	var d = new Date();
	d.setTime(d.getTime()+(exdays*24*60*60*1000));
	var expires = "expires="+d.toGMTString();
	document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname)
{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++) 
	{
		var c = ca[i].trim();
		if (c.indexOf(name)==0) 
		{
			uname = c.substring(name.length,c.length);
			return uname;
		}
	}
	return "";
}

function checkCookie()
{
	var user=getCookie("username");
	if (user!="")
	{
		$('#buttom').before("<h1>Welcome " + user + '</h1>');
	}
	else 
	{
		user = prompt("Please enter your name:","");
		if (user!="" && user!=null)
		{
			setCookie("username",user,30);
			uname = user;
		}
	}
}

var area = document.getElementById("input-text");

area.ondragenter = function(ev) {
    ev.preventDefault();
    //this can do somethings
    //ps:show this img
};
//prevent open pic
//must have
area.ondragover = function(ev) {
    ev.preventDefault();
};
//when 
area.ondrop = function(ev) {
    ev.preventDefault();
    var dt = ev.dataTransfer;
    var file = dt.files[0];

    //just can upload img
    var format = new RegExp('image/*')
    if(!format.test(file.type))
    {
        $('#buttom').before('<h2>Please upload image!!!</h2>');
        return ;        
    }
    // check this file md5
    //if exist ,send img tag
    //else upload

	getMd5(file,function(md5){

		console.log(md5);
                var exten = file.name.split('.').pop();
		//test this img is exist in server
		//to make sure send msg or upload
		try{
			myImage.src = 'http://7xo1fz.com1.z0.glb.clouddn.com/'+md5+'.'+exten;
		}catch(err){}
		myImage.onload=function(){
			//already exist
			$('#buttom').before('<h4 class="me">me&nbsp;&nbsp;:&nbsp;&nbsp;<img src="'+myImage.src+'"></h4>');
			websocket.send(uname+':<img src="'+myImage.src+'">');
		}
		myImage.onerror = function(){
			//no exist,upload
			console.log("not exist");
			upload(file,function(res){
				//return the img url
	        	console.log(res);
	        	// $('#buttom').before('<p class="me">me  :  <img src="'+res+'"></p>')
	        })
			
		}
	})

    
};

//use ajax upload img
function upload(file,callback){

	var foda = new FormData();
	//add username
	foda.append("username",uname);
	foda.append("img",file);
	$.ajax({
	    url: '/upload',
	    type: 'POST',
	    cache: false,
	    data: foda,
	    processData: false,
	    contentType: false
	}).done(function(res) {
		callback(res);
	}).fail(function(res) {
		console.error(res);
	});

}


checkCookie();
connectWS();
